package de.velvettear.squirrel.gui;

import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import de.velvettear.squirrel.R;
import de.velvettear.squirrel.kernel.Settings;
import de.velvettear.squirrel.kernel.Statics;
import de.velvettear.squirrel.util.AnimationHelper;
import de.velvettear.squirrel.util.ChatHelper;
import de.velvettear.squirrel.util.MySQLHelper;

public class SettingsFrame extends FragmentActivity implements ActionBar.TabListener {
			
	private static Activity activity;
	
	private static ViewPager viewPager;
	private static SectionsPagerAdapter sectionsPagerAdapter;	
				
	// ChatSettingsFragment
	private static Switch sw_status;
	private static LinearLayout ll_data;
	private static EditText et_alias;
	private static TextView tv_info;
	private static RelativeLayout rl_info;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_networkframe);

		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		
		activity = this;
		
		sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

		viewPager = (ViewPager) findViewById(R.id.pager);
		viewPager.setAdapter(sectionsPagerAdapter);

		viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				actionBar.setSelectedNavigationItem(position);
			}
		});

		for (int i = 0; i < sectionsPagerAdapter.getCount(); i++) {
			actionBar.addTab(actionBar.newTab().setText(sectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
			actionBar.newTab();
		}	
					
		if (getIntent().hasExtra(Statics.COMMAND)) {
			String command = getIntent().getExtras().getString(Statics.COMMAND);
			
			if (command.equals(Statics.COMMAND_SETTINGS_CHAT)) {
				viewPager.setCurrentItem(Statics.ID_SETTINGSFRAGMENT_CHATSETTINGS);	
			}
		}		
	}
		
	@Override
	public void onDestroy() {	
		super.onDestroy();
		
		String currentAlias = new Settings().getValueByName(Statics.SETTINGS_CHAT_ALIAS);
		String newAlias = et_alias.getText().toString();
		if (!newAlias.equals(currentAlias)) {
			boolean isChecked = sw_status.isChecked();
			saveSettings(isChecked, true);
		} 
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {		
//		getMenuInflater().inflate(R.menu.menu_settingsframe, menu);	
				
		return super.onCreateOptionsMenu(menu);	
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
				
		case R.id.menu_settingsframe_save:
			break;
			
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		invalidateOptionsMenu();
		viewPager.setCurrentItem(tab.getPosition());		
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		
	}
		
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);						
	}
		
	private static int getCurrentFragment() {
		return (int) sectionsPagerAdapter.getItemId(viewPager.getCurrentItem());
	}
	
	public static void saveSettings(boolean active) {
		saveSettings(active, false);
	}
	
	public static void saveSettings(boolean active, boolean mysql) {
		final boolean isActive = active;
		final boolean useMysql = mysql;
		
		AsyncTask<Void, Void, Void> saveTask = new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... params) {
				Settings settings = new Settings();
				settings.getSettingsByName(Statics.SETTINGS_CHAT_ACTIVATED);
				if (settings.isValid()) {
					if (isActive) {
						settings.m_sValue = Statics.STATUS_ACTIVE;
					} else {
						settings.m_sValue = Statics.STATUS_INACTIVE;
					}			
					settings.store();
				}
				
				settings = new Settings();
				settings.getSettingsByName(Statics.SETTINGS_CHAT_ALIAS);
				if (settings.isValid()) {
					settings.m_sValue = et_alias.getText().toString();
					settings.store();
				}
				
				if (isActive && useMysql) {
					String username = new Settings().getValueByName(Statics.SETTINGS_CHAT_USERNAME);
					String alias = new Settings().getValueByName(Statics.SETTINGS_CHAT_ALIAS);
					String password = new Settings().getValueByName(Statics.SETTINGS_CHAT_PASSWORD);
					
					MySQLHelper.createOrUpdateJabberUser(username, alias, password);
				}
				return null;
			}
			
		}; 
		
		saveTask.execute();
				
	}
	
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			switch (position) {
						
			case 0: return ChatSettingsFragment.newInstance();
			
			default: return ChatSettingsFragment.newInstance();
			
			}
		}

		@Override
		public int getCount() {	
			return 1;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0:
				return Statics.CHAT;
			}
			return null;
		}
	}
			
	public static class ChatSettingsFragment extends Fragment implements OnCheckedChangeListener {
		
		public ChatSettingsFragment() {
		
		}

		public static ChatSettingsFragment newInstance() {
			ChatSettingsFragment fragment = new ChatSettingsFragment();
			return fragment;
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_chatsettings, container, false);
			
			sw_status = (Switch) rootView.findViewById(R.id.chatsettings_switch);	
			ll_data = (LinearLayout) rootView.findViewById(R.id.chatsettings_ll_data);
			et_alias = (EditText) rootView.findViewById(R.id.chatsettings_et_alias_value);
			et_alias.setText(new Settings().getValueByName(Statics.SETTINGS_CHAT_ALIAS));			
			rl_info = (RelativeLayout) rootView.findViewById(R.id.chatsettings_rl_info);
			tv_info = (TextView) rootView.findViewById(R.id.chatsettings_tv_info);
				
			String chat_status = new Settings().getValueByName(Statics.SETTINGS_CHAT_ACTIVATED);
			if (chat_status.equals(Statics.STATUS_ACTIVE)) {
				ll_data.setVisibility(View.VISIBLE);
				sw_status.setChecked(true);
			} else {
				ll_data.setVisibility(View.GONE);
				sw_status.setChecked(false);
			}			
			sw_status.setOnCheckedChangeListener(this);
						
			return rootView;
		}
				
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			switch (buttonView.getId()) {
				
			case R.id.chatsettings_switch:
				sw_status.setClickable(false);
				saveSettings(isChecked);
				if (isChecked) {
					tv_info.setText("Connecting");
					AnimationHelper.startAnimation(rl_info, true);
					ChatHelper.registerAccount(guiHandler);
				} else {
					ll_data.setVisibility(View.GONE);
					tv_info.setText("Disconnecting");
					AnimationHelper.startAnimation(rl_info, true);
					ChatHelper.unregisterAccount(guiHandler);
				}
				break;
			
			}			
		}
			
	}	
	
	public static Handler guiHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle data = msg.getData();
		
			if (data.containsKey(Statics.COMMAND_CHAT_ACCOUNTCREATION)) {
				String message = data.getString(Statics.COMMAND_CHAT_ACCOUNTCREATION);
				if (message.equals(Statics.STATUS_SUCESS)) {
					ll_data.setVisibility(View.VISIBLE);
				} else if (message.equals(Statics.STATUS_ERROR)) {
					
				}				
				AnimationHelper.stopAnimation(rl_info, true);
				sw_status.setClickable(true);
			} else if (data.containsKey(Statics.COMMAND_CHAT_ACCOUNTDELETION)) {
				String message = data.getString(Statics.COMMAND_CHAT_ACCOUNTDELETION);
				if (message.equals(Statics.STATUS_SUCESS)) {
				
				} else if (message.equals(Statics.STATUS_ERROR)) {
					
				}					
				AnimationHelper.stopAnimation(rl_info, true);
				sw_status.setClickable(true);
			} 
		}
	};
	
}
